<?php

namespace App\Http\Controllers\Logic;

use App\Http\Controllers\Controller;
use App\Model\OAPosition;
use App\Model\OAPositionAuth;
use App\Model\OAStaff;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class personnelLogic extends Controller
{
    public function addStaff($input){
        try{
            DB::beginTransaction();
            $isExists = OAStaff::query()->where('account',$input['account'])->exists();
            if($isExists) throw new \Exception('账号'.$input['account'].'已存在,请重新输入');
            $input['created_at'] = $input['updated_at'] = date('Y-m-d H:i:s');
            $input['password'] = md5($input['password']);
            $staff_id = OAStaff::query()->insertGetId($input);
            DB::commit();
            return $staff_id;
        }catch (\Exception $e){
            DB::rollBack();
            throw new \Exception($e->getMessage());
        }
    }

    public function getAuthList()
    {
        $list = OAPosition::query()->select()->get(['id','title','authid'])->toArray();

        foreach ($list as &$val){
            $val['authid'] = explode(',',$val['authid']);
            $auth = OAPositionAuth::query()->whereIn('id',$val['authid'])->pluck('title')->toArray();
            $val['auth'] = implode(',',$auth);
        }
        $authList['list'] = $list;
        $authList['model'] = OAPositionAuth::query()->pluck('title','id')->toArray();
        return $authList;
    }

    //获取模块列表
    public function getModelList()
    {
        $data['list'] = OAPositionAuth::query()->select('*')->get()->toArray();
        foreach ($data['list'] as &$val){
            if(!Str::contains($val['icon'],['http','https'])){
                $val['icon'] = env('APP_URL') . $val['icon'];
            }
        }
        $data['typeList'] = [1=>'常用功能',2=>'业务办理',3=>'代办事项'];
        return $data;
    }

    //编辑权限
    public function editAuth($params)
    {
        try{
            DB::beginTransaction();
            $newID = 0;
            if(!empty($params['id'])){
                $authInfo = OAPosition::query()->where('id',$params['id'])->first();
                $authInfo->title = $params['title'];
                $authInfo->authid = implode(',',$params['authid']);
                $authInfo->save();
                $newID = $params['id'];
            }else{
                $isExists = OAPosition::query()->where('title',$params['title'])->exists();
                if($isExists) throw new \Exception('职位'.$params['title'].'已存在');
                $insetData = [
                    'authid'=>implode(',',$params['authid']),
                    'title'=>$params['title'],
                    'created_at'=>date('Y-m-d H:i:s'),
                    'status'=>1,
                ];
                $newID = OAPosition::query()->insertGetId($insetData);
            }

            DB::commit();
            return $newID;
        }catch (\Exception $e){
            DB::rollBack();
            throw new \Exception($e->getMessage());
        }
    }


    //编辑权限
    public function editModel($params)
    {
        try{
            DB::beginTransaction();
            $newID = 0;
            if(!empty($params['id'])){
                $authInfo = OAPositionAuth::query()->where('id',$params['id'])->first();
                $authInfo->title = $params['title'];
                $authInfo->icon = $params['icon'];
                $authInfo->path = $params['path'];
                $authInfo->type = $params['type'];
                $authInfo->save();
                $newID = $params['id'];
            }else{
                $isExists = OAPositionAuth::query()->where('title',$params['title'])->exists();
                if($isExists) throw new \Exception('模块'.$params['title'].'已存在');
                $insetData = [
                    'title'=>$params['title'],
                    'icon'=>$params['icon'],
                    'path'=>$params['path'],
                    'type'=>$params['type'],
                    'created_at'=>date('Y-m-d H:i:s'),
                    'status'=>0,
                ];
                $newID = OAPositionAuth::query()->insertGetId($insetData);
            }

            DB::commit();
            return $newID;
        }catch (\Exception $e){
            DB::rollBack();
            throw new \Exception($e->getMessage());
        }
    }

    //编辑用户信息
    public function editStaffMsg($params)
    {
        DB::beginTransaction();
        try{
            $editRoleId = $params['roleid'];
            $enableEditRole = [95,221,210,219];
            $executiveRoleList = [212, 213, 214, 215, 218, 219, 220, 224, 227,223];
            $executiveRoleid = 219;
            $executiveEditFields = [''];
            $userinfo = OAStaff::query()->where('account',$params['account'] ?? '')->first();
            if(is_null($userinfo)) throw new \Exception('用户不存在');
            $updateData = [];
            if(isset($params['newPassword']) || isset($params['repeatPassword'])){
                if($params['newPassword'] != $params['repeatPassword']) throw new \Exception('两次密码不一致');
                $newPwd = md5($params['newPassword']);
                $oldPwd = $params['password'];
                if($userinfo->password != md5($oldPwd)) throw new \Exception('旧密码错误请重新输入');
                $updateData['password'] = $newPwd;
                unset($params['repeatPassword'],$params['newPassword']);
            }
            if(isset($params['account']) && !empty($params['account'])){
                $updateData['account'] = $params['account'];
            }
            if(isset($params['avatar']) && !empty($params['avatar'])){$updateData['avatar'] = $params['avatar'];}
            if(isset($params['email']) && !empty($params['email'])){$updateData['email'] = $params['email'];}

            if(isset($params['id_card']) && !empty($params['id_card'])){$updateData['id_card'] = $params['id_card'];}
            if(isset($params['identify']) && !empty($params['identify'])){$updateData['identify'] = $params['identify'];}
            if(isset($params['marriage']) && !empty($params['marriage'])){$updateData['marriage'] = $params['marriage'];}
            if(isset($params['graduate_date']) && !empty($params['graduate_date'])){$updateData['graduate_date'] = $params['graduate_date'];}
            if(isset($params['job_date']) && !empty($params['job_date'])){$updateData['job_date'] = $params['job_date'];}
            if(isset($params['professional']) && !empty($params['professional'])){$updateData['professional'] = $params['professional'];}
            if(isset($params['registered_place']) && !empty($params['registered_place'])){$updateData['registered_place'] = $params['registered_place'];}
            if(isset($params['native_place']) && !empty($params['native_place'])){$updateData['native_place'] = $params['native_place'];}
            if(isset($params['zip_code']) && !empty($params['zip_code'])){$updateData['zip_code'] = $params['zip_code'];}
            if(isset($params['telephone']) && !empty($params['telephone'])){$updateData['telephone'] = $params['telephone'];}
            if(isset($params['address']) && !empty($params['address'])){$updateData['address'] = $params['address'];}

            if(isset($params['phone']) && !empty($params['phone'])){$updateData['phone'] = $params['phone'];}
            if(isset($params['current_address']) && !empty($params['current_address'])){$updateData['current_address'] = $params['current_address'];}
            if(isset($params['company_email']) && !empty($params['company_email'])){$updateData['company_email'] = $params['company_email'];}
            if(isset($params['main_position_id']) && !empty($params['main_position_id'])){$updateData['position_id'] = $params['main_position_id'];}
            if(isset($params['hiredate']) && !empty($params['hiredate'])){$updateData['hiredate'] = $params['hiredate'];}
            if(isset($params['positive_date']) && !empty($params['positive_date'])){$updateData['positive_date'] = $params['positive_date'];}
            if(isset($params['expire_date']) && !empty($params['expire_date'])){$updateData['expire_date'] = $params['expire_date'];}
            if(isset($params['renew_date']) && !empty($params['renew_date'])){$updateData['renew_date'] = $params['renew_date'];}

            if(isset($params['note']) && !empty($params['note'])){$updateData['note'] = $params['note'];}
            if(isset($params['desc']) && !empty($params['desc'])){$updateData['desc'] = $params['desc'];}
            if(isset($params['realname']) && !empty($params['realname'])){$updateData['username'] = $params['realname'];}

            if(isset($params['deptid_list']) && !empty($params['deptid_list'])){
                $deptList = array_filter($params['deptid_list']);
                if(!empty($deptList))$updateData['deptid'] = implode(',',$deptList);
            }
            if(isset($params['role_list']) && !empty($params['role_list'])){
                $roleList = array_filter($params['role_list']);
                if(!empty($roleList))$updateData['roleid'] = implode(',',$roleList);
            }
            //行政总监分配职位
            if($editRoleId == $executiveRoleid){
                if(isset($params['role_list']) && !empty($params['role_list'])){
                    $roleList = array_filter($params['role_list']);
                    //dd($roleList);
                    if($roleList) {
                        foreach ($roleList as $role) {
                            if (!in_array($role, $executiveRoleList)) throw new \Exception('行政总监只能任命总监及总监以下的职位');
                        }
                    }
                }
            }

            $userinfo->update($updateData);
            DB::commit();
            return true;

        }catch (\Exception $e){
            DB::rollBack();
            dd($e);
            throw new \Exception($e->getMessage());
        }
    }

    //删除用户
    public function delStaff($params)
    {
        return OAStaff::query()->where('id',$params['uid'])->delete();
    }


    //修改密码
    public function editStaffMsgBySelf($params)
    {

        $userinfo = OAStaff::where('account',$params['account'])->first();
        if(is_null($userinfo)) throw new \Exception('账号不存在');
        if(isset($params['password']) || isset($params['repeatPassword'])){
            if($params['password'] != $params['repeatPassword']) throw new \Exception('两次密码不一致');
            $newPwd = md5($params['password']);
            $userinfo->password = $newPwd;
            $userinfo->save();
        }

        return true;
    }
}
